﻿using System.Data;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.IO.Compression;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.Xml;
using System.Speech.Synthesis;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using LitJson;
using Sunny.UI;
using Sunny.UI.Win32;
using static Erp.RawInput;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;

namespace Erp
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            ApplicationConfiguration.Initialize();
            Application.Run(new View());
        }
    }

    public static class Controller
    {
        public static Model model { get; set; }
        public static View view { get; set; }

        public static SpeechSynthesizer speech = new();

        public static View_系统设置 系统设置 = null;
        public static View_验货窗口 验货窗口 = null;

        public static List<View_订单> 集合_view_订单 = new();
        public static List<View_订单> 集合_view_订单_New = new();
        public static  List<View_订单> 集合_勾选订单 = new();

        public static bool 启动验货枪识别 = false;
        public static bool 启动发货枪识别 = false;
        public static bool hookMessage = false;

        public static string 验货枪识别码 = ErpSettings.Default.验货枪识别码;
        public static string 发货枪识别码 = ErpSettings.Default.发货枪识别码;
        public static StringBuilder 验货枪缓存 = new();
        public static StringBuilder 发货枪缓存 = new();

        public static bool 验货单号锁定 = false;
        public static int Body内容 = 0;
        /// <summary>
        /// 0:无内容 1:待打印订单 2:待发货订单 3:系统设置 4:验货
        /// </summary>

        public static string 车签 { get { return ("BQ240094" + ((DateTime.Now - Convert.ToDateTime("2025-09-12")).Days + 1980).ToString().PadLeft(6, '0')); } }

        public static void CtrlFactory(string key, params object[] 参数)
        {
            Task.Run(async() => {
                switch (key)
                {
                    case "初始化View":
                        view = 参数[0] as View;
                        model = new Model();

                        //原始数据接收
                        view.Invoke(() => { RawInput.订阅WM_INPUT信息(view.Handle); }) ;

                       
                        //erp登录
                        await model.UserLogin();
                        return;
                        while (true)
                        {
                            view.更新UI_待打印(await model.获取数据_待打印数量());
                            view.更新UI_待发货(await model.获取数据_待发货数量());

                            await Task.Delay(5 * 60 * 1000);
                        }

                    case "待打印Click":
                        await model.获取数据_待打印订单();
                        view.更新UI_Body_订单集合();
                        Body内容 = 1;
                        return;

                    case "待发货Click":  
                        await model.获取数据_待发货订单();
                        view.更新UI_Body_订单集合();
                        Body内容 = 2;
                        return;

                    case "系统设置Click":
                        view.更新UI_Body_系统设置();
                        Body内容 = 3;
                        return;

                    case "处理原始输入信息":
                        var data = 参数[0] as RawInputData;
                        JsonData jsonObject = null;
                        switch (data.deviceName)
                        { 
                            case string s when s == 验货枪识别码:
                                hookMessage = true;

                                if (data.message == "ENTER")
                                {
                                    if (验货单号锁定) { speech.SpeakAsync("订单备注未确认"); 验货枪缓存.Clear(); return; }

                                    // if (province.Contains("甘肃") || province.Contains("宁夏") || province.Contains("青海")) Controller.view_MainForm.btnWeight.BeginInvoke(() => { Controller.view_MainForm.btnWeight.Text = "3.0"; });
                                    CtrlFactory("验货");
                                   
                                }
                                else 验货枪缓存.Append(data.message);

                                return;

                            case string s when s == 发货枪识别码:
                                hookMessage = true;
                                if (data.message == "ENTER")
                                {
                                    CtrlFactory("发货");
                                }
                                else 发货枪缓存.Append(data.message);
                                return;

                            default:
                                hookMessage = false;

                                if (启动验货枪识别)
                                {
                                    系统设置.Invoke(() => { 系统设置.txt验货枪识别码.Text = data.deviceName; 系统设置.chk识别验货枪.Checked = false; });
                                }
                                else if(启动发货枪识别)
                                {
                                    系统设置.Invoke(() => { 系统设置.txt发货枪识别码.Text = data.deviceName;系统设置.chk识别发货枪.Checked = false; });    
                                }

                                return;
                        }


                        return;

                    case "验货":
                        
                        var 验货_单号查询结果 = await model.获取数据_查询指定快递单号(验货枪缓存.ToString());

                        if (null == 验货_单号查询结果) { speech.SpeakAsync("查询单号请求异常！"); 验货枪缓存.Clear(); return; }

                        if (验货_单号查询结果["message"].ToString() != "ok") { speech.SpeakAsync("查询单号请求错误！"); 验货枪缓存.Clear(); return; }

                        if (((int)验货_单号查询结果["data"]["total"]) == 0) { speech.SpeakAsync("单号不存在！"); 验货枪缓存.Clear(); return; }

                        view.更新UI_Body_验货();
                        
                        //验货
                        Body内容 = 4;
                        return;

                    case "回收单号":                       
                        var 回收单号_返回值 = await model.回收快递单号(参数[0] as string, 参数[1] as string);

                        if (回收单号_返回值["message"].ToString() !="ok") speech.SpeakAsync("单号回收失败！");

                        if (回收单号_返回值["data"]["successCount"].ToString()!="1") speech.SpeakAsync("单号回收失败！");

                        speech.SpeakAsync("单号回收成功！");
                        验货枪缓存.Clear();
                        发货枪缓存.Clear();
                        return;

                    case "发货":
                        var 发货_单号查询结果 = await model.获取数据_查询指定快递单号(发货枪缓存.ToString());

                        Debug.WriteLine(发货_单号查询结果.ToJsonStr());
                        if (null == 发货_单号查询结果) { speech.SpeakAsync("查询单号请求异常！"); 发货枪缓存.Clear(); return; }

                        if (发货_单号查询结果["message"].ToString() != "ok") { speech.SpeakAsync("查询单号请求错误！"); 发货枪缓存.Clear(); return; }

                        if (((int)发货_单号查询结果["data"]["total"]) == 0) { speech.SpeakAsync("单号不存在！"); 发货枪缓存.Clear(); return; }

                        if ((int)发货_单号查询结果["data"]["items"][0]["status"] == 7) { speech.SpeakAsync("订单已关闭！"); CtrlFactory("回收单号", [发货_单号查询结果["data"]["items"][0]["id"].ToString(), 发货枪缓存.ToString()]);return; }

                        if ((int)发货_单号查询结果["data"]["items"][0]["status"] == 5) { CtrlFactory("揽发合一");return;  }

                        jsonObject =发货_单号查询结果["data"]["items"][0];
                       
                        var 发货_结果 = await model.发货(jsonObject["cpCode"].ToString(), jsonObject["id"].ToString(), jsonObject["waybillNo"].ToString(), jsonObject["mergeFlag"].ToString(), jsonObject["orderId"].ToString(), jsonObject["platformCode"].ToString(), jsonObject["sysOrderId"].ToString(), jsonObject.ContainsKey("mergeOrderIds") ? jsonObject["mergeOrderIds"].ToString() : "");
                        Debug.WriteLine(11111);

                        if (发货_结果["message"].ToString() == "ok")
                        {
                             CtrlFactory("揽发合一");
                        }
                        else
                        {
                            speech.SpeakAsync("发货失败");
                            发货枪缓存.Clear();
                        }
                        return;

                    case "揽收":
                        return;

                    case "揽发合一":
                        //speech.SpeakAsync("发货成功");
                        //发货枪缓存.Clear();
                        //return;

                        var 结果_获取目的地 = await model.获取目的地数据(发货枪缓存.ToString());

                        if (结果_获取目的地["code"].ToString() == "200" || 结果_获取目的地["code"].ToString() == "644")
                        {
                            string desOrgCode = 结果_获取目的地["data"]["desSrcOrg"].ToString();
                            string desOrgName = DesOrg.Name.ContainsKey(desOrgCode) ? DesOrg.Name[desOrgCode] : "未知网点";

                            if (desOrgName == "未知网点") { speech.SpeakAsync("已发货，网点未匹配。无法揽收"); 发货枪缓存.Clear(); Debug.WriteLine(desOrgCode); return; }

                            var 结果_揽发合一 = await model.揽发合一操作(车签, desOrgCode, DesOrg.Name[desOrgCode], 发货枪缓存.ToString());
                          
                            
                            
                            
                            Debug.WriteLine(结果_揽发合一.ToJsonStr());///////////////////////////////////////////////////////////




                            if ((bool)结果_揽发合一["success"])
                            {
                                speech.SpeakAsync("揽收成功");
                            }
                            else
                            {
                                speech.SpeakAsync("揽收失败");
                                Debug.WriteLine(结果_揽发合一.ToJsonStr());
                            }

                        }
                        else if (结果_获取目的地["code"].ToString() == "629" || 结果_获取目的地["code"].ToString() == "642")
                        {
                            speech.SpeakAsync("订单已揽收");
                        }
                        else if (结果_获取目的地["code"].ToString() == "604")
                        {
                            speech.SpeakAsync("发货拦截，订单已退款");
                        }
                        else
                        {
                            speech.SpeakAsync("揽收失败");
                            Debug.WriteLine(结果_获取目的地["code"].ToString());
                            Debug.WriteLine(车签);
                        }
                        发货枪缓存.Clear();
                        return;

                    case "打印":
                      //  model.ModelFactory("获取Waybill",)
                        break;
                }
                
            });
        }



        # region 扩展·View·订单
        public static void SetCheckState(this View_订单 订单, bool check)
        {
            if (check)
            {
                订单.btn勾选.Checked = true;
                订单.BackColor = Color.FromArgb(244, 242, 251);
                集合_勾选订单.Add(订单);
            }
            else
            {
                订单.btn勾选.Checked = false;
                订单.BackColor = Color.FromArgb(253, 249, 241);
                集合_勾选订单.Remove(订单);
            }
        }
        public static async void 更新UI_View_订单(this View_订单 订单)
        {
            订单.btn平台.Text = 订单.platformCode == "KHTAOBAO" ? "淘宝-" + 订单.mallName : 订单.platformCode == "PDD" ? "拼多多-" + 订单.mallName : 订单.platformCode == "KS" ? "快手-" + 订单.mallName : 订单.platformCode == "LUBAN" ? "抖店-" + 订单.mallName : "线下订单";
            订单.lab订单号.Text = 订单.orderId;
            订单.lab发货时间.Text = 订单.lastShipTime;
            订单.lab备注.Text = 订单.buyerWords + "\r\n" + 订单.sellerWords;
            订单.lab_name.Text = 订单.receiveNameSensitive;
            订单.lab_phone.Text = 订单.receiveMobileSensitive;
            订单.lab_address.Text = 订单.receiveProvince + "-" + 订单.receiveCity + "-" + 订单.receiveTown + "-" + 订单.receiveDetailSensitive;

            if (订单.erpProducts.Count > 0)
            {
                int index = 0;
                foreach (var p in 订单.erpProducts)
                {
                    //数量匹配
                    if (订单.erpProducts.Count > 订单.图片集合.Count)
                    {
                        var pic = new View_图片();
                        订单.pnl图片.Add(pic);
                        订单.图片集合.Add(pic);
                    }
                    else if (订单.erpProducts.Count < 订单.图片集合.Count)
                    {
                        订单.图片集合[订单.图片集合.Count - 1].Dispose();
                    }

                    订单.图片集合[index].img.Image = p.productPic.Length > 0 ? await p.productPic.ToImage() : null;
                    订单.图片集合[index].lab数量.Text = p.productNumber.ToString();

                    index++;
                }
            }
            else if (订单.mergeSubOrders.Count > 0)
            {
                //获取图片总数量
                int totalCount = 0;
                foreach (var subOrder in 订单.mergeSubOrders)
                {
                    if (subOrder.orderStatus != "6")
                        totalCount += subOrder.erpProducts.Count;
                }

                int index = 0;
                foreach (var subOrder in 订单.mergeSubOrders)
                {
                    if (subOrder.orderStatus != "6")
                    {
                        foreach (var p in subOrder.erpProducts)
                        {
                            //数量匹配
                            if (totalCount > 订单.图片集合.Count)
                            {
                                var pic = new View_图片();
                                订单.pnl图片.Add(pic);
                                订单.图片集合.Add(pic);
                            }
                            else if (totalCount < 订单.图片集合.Count)
                            {
                                订单.图片集合[订单.图片集合.Count - 1].Dispose();
                            }

                            订单.图片集合[index].img.Image = p.productPic.Length > 0 ? await p.productPic.ToImage() : null;
                            订单.图片集合[index].lab数量.Text = p.productNumber.ToString();

                            index++;
                        }

                    }
                }
            }
        }
        public static void 打印(this View_订单 订单,JsonData data)
        {
            if (data["status"].ToString() != "200") { Controller.speech.SpeakAsync("获取快递单号失败"); return; }

            var printData = JsonMapper.ToObject(data["data"][0]["waybillNoList"][0]["printData"].ToString());
            string 商品info = "111111111";
            string 备注info = "222222222";
            string printXML = $@"<?xml version=\""1.0\"" encoding=\""UTF-8\""?>\n 
                                <layout  xmlns=\""http://cloudprint.cainiao.com/print\"" xmlns:xsi=\""http://www.w3.org/2001/XMLSchema-instance\"" xsi:schemaLocation=\""http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd\"" xmlns:editor=\""http://cloudprint.cainiao.com/schema/editor\"" id=\""CUSTOM_AREA\"" width=\""72\"" height=\""40\"">\n
                                    <layout editor:_for_=\""1592295795243879\"" id=\""1592295795243970\"" width=\""72\"" left=\""0.5\"" top=\""0\""  style=\""zIndex:1;\"">\n
                                        <layout width=\""72\"" height=\""20.0\"" left=\""0.5\"" top=\""0\"">\n
                                            <text style=\""fontFamily:SimHei;fontSize:10;align:undefined;fontWeight:no;fontItatlic:false;\"">
                                                <![CDATA[{商品info}]]>
                                            </text>\n
                                        </layout>\n
                                        <layout width=\""72\"" height=\""5.0\"" left=\""0.5\"" top=\""21\"">\n            
                                            <text style=\""fontFamily:SimHei;fontSize:8;align:left;fontWeight:no;fontItatlic:false;\"">
                                                <![CDATA[{备注info}]]>
                                            </text>\n          
                                        </layout>\n
                                    </layout>\n        
                                </layout>
            ";

            string printStr = $@"{{
                ""cmd"":""print"",                 
                ""printer"":""{data["data"][0]["defaultPrint"].ToString()}"",
                ""taskId"":""{data["data"][0]["mailNo"].ToString()}|{订单.orderId}"",
                ""firstDocumentNumber"":1,
                ""totalDocumentCount"":1,
                ""documents"":[{{
                    ""documentID"":""{订单.orderId}"",
                    ""printData"":{{
                        ""encryptedData"":""{printData["encryptedData"].ToString()}"",
                        ""signature"":""{printData["signature"]}"",
                        ""templateURL"":""{printData["templateURL"]}"",
                        ""ver"":""{printData["ver"]}""}},
                    ""expressPrintType"":""CUST-CN"",
                    ""customData"":{{
                        ""printXML"":""{printXML}"" }},
                    ""addData"":{{}}
                        ""sender"":{{
                            ""address"":{{
                                ""detail"":
                            }}
                        }} }}]
            }}"; 
        }
        public static async void 申请单号并打印(this View_订单 订单)
        {
            var data = await model.获取数据_申请1个新快递单号(订单);
            订单.打印(data);
            Debug.WriteLine(data.ToJsonStr());
        }

        #endregion








        #region 扩展·View
        public static async void 更新UI_待打印(this View view,string text)
        {
            await view.btn待打印.InvokeAsync(() => { view.btn待打印.Text = $"待打印：{text}"; });       
        }
        public static async void 更新UI_待发货(this View view,string text)
        {
            await view.btn待发货.InvokeAsync(() => { view.btn待发货.Text = $"待发货：{text}"; });
        }
        public static void 更新UI_清除_Body内容(this View view,int body内容)
        {
            switch (Body内容)
            {
                case 0:
                    return;

                case 1:
                    goto case 2;
                    
                case 2:
                    if (view.Body.AllControls.Count == 0) return;

                    view.Body.AllControls.Clear();
                    foreach (var item in new List<View_订单>(集合_view_订单)) { item.Dispose(); }
                    集合_view_订单.Clear();
                    return;

                case 3:
                    if (body内容 == 3) return;

                    return;
                case 4:
                    return;
            }

            
        }

        private static void 更新UI_清除Body内容1_2(this View view)
        {
            if (view.Body.AllControls.Count == 0) return;

            view.Body.AllControls.Clear();
            foreach (var item in new List<View_订单>(集合_view_订单)) { item.Dispose(); }
            集合_view_订单.Clear();
        }
        private static void 更新UI_清除Body内容3(this View view)
        {
           
        }




        public static async void 更新UI_Body_订单集合(this View view)
        {
            await view.Body.InvokeAsync(() =>
            {
                if (集合_view_订单_New.Count == 0) { view.更新UI_清除_Body内容(2); return; }

                view.Body.Size = new Size(view.Body.Width, 895);
               
                view.更新UI_清除_Body内容(2);

                foreach (var item in 集合_view_订单_New)
                {
                    集合_view_订单.Add(item);
                    view.Body.Add(item);
                    item.更新UI_View_订单();
                }
            });
            // 确保UI更新完成
            await Task.Delay(100);
        }
        public static async void 更新UI_Body_系统设置(this View view)
        {
            if(系统设置 != null) return;

            await view.Body.InvokeAsync(() =>
            {            
                view.更新UI_清除_Body内容(3);
                系统设置 = new();
                view.Body.Add(系统设置);
             
            });
            // 确保UI更新完成
            await Task.Delay(100);
        }
        public static async void 更新UI_Body_验货(this View view)
        {
            view.Body.Invoke(() =>
            {
                view.更新UI_清除_Body内容(4);

                验货窗口 = new View_验货窗口();
                view.Body.Add(验货窗口);
            });
        }
        #endregion


        #region 扩展·JsonData
        public static string Return_Count(this JsonData json)
        {
            if (null == json) { Controller.speech.SpeakAsync("获取待发货数据失败"); return "0"; }

            if (json["status"].ToString() != "200") { Controller.speech.SpeakAsync("获取待发货数据失败"); return "0"; }

            return json["data"]["total"].ToString();
        }
        public static void To集合_View_订单(this JsonData json)
        {
            if (null == json) { Controller.speech.SpeakAsync("获取待发货数据失败"); return; }


            if (json["status"].ToString() != "200") { Controller.speech.SpeakAsync("获取待发货数据失败"); return; }


            if (json["data"]["total"].ToString() == "0") return;

            集合_view_订单_New.Clear();

            foreach (JsonData item in json["data"]["items"])
            {
                View_订单 view_订单 = item.ToView_订单();

                if (item.ContainsKey("erpProducts"))
                {
                    view_订单.erpProducts = item["erpProducts"].ToErpProducts();
                }
                else if (item.ContainsKey("mergeSubOrders"))
                {
                    view_订单.mergeId = item["mergeId"].ToString();
                    view_订单.mergeSubOrders = item["mergeSubOrders"].ToMergeSubOrders();   
                }

                //快递单号
                if (item.ContainsKey("logisticsCodes"))
                {
                    view_订单.logisticsCodes = item["logisticsCodes"].ToLogisticsCode();
                }

                集合_view_订单_New.Add(view_订单);
            }
        }
        //step 1
        public static View_订单 ToView_订单(this JsonData item)
        {
            return new View_订单
            {
                id = item["id"].ToString(),
                platformCode = item["platformCode"].ToString(),
                mallCode = item["mallCode"].ToString(),
                mallName = item["mallName"].ToString(),
                orderId = item["orderId"].ToString(),
                sysOrderId = item["sysOrderId"].ToString(),
                orderStatus = item["orderStatus"].ToString(),
                cpCode = item.ContainsKey("cpCode") ? item["cpCode"].ToString() : "",
                cpCodeName = item.ContainsKey("cpCodeName") ? item["cpCodeName"].ToString() : "",
                cpCodeTempId = item.ContainsKey("cpCodeTempId") ? item["cpCodeTempId"].ToString() : "",
                receiveNameSensitive = item.ContainsKey("receiveNameSensitive") ? item["receiveNameSensitive"].ToString() : "",
                receiveMobileSensitive = item.ContainsKey("receiveMobileSensitive") ? item["receiveMobileSensitive"].ToString() : "",
                receiveProvince = item.ContainsKey("receiveProvince") ? item["receiveProvince"].ToString() : "",
                receiveCity = item.ContainsKey("receiveCity") ? item["receiveCity"].ToString() : "",
                receiveTown = item.ContainsKey("receiveTown") ? item["receiveTown"].ToString() : "",
                receiveDetailSensitive = item.ContainsKey("receiveDetailSensitive") ? item["receiveDetailSensitive"].ToString() : "",
                sellerWords = item.ContainsKey("sellerWords") ? item["sellerWords"].ToString() : "",
                buyerWords = item.ContainsKey("buyerWords") ? item["buyerWords"].ToString() : "",
                mergeFlag = item.ContainsKey("mergeFlag") ? item["mergeFlag"].ToString() : "",
                mergeOrderIds = item.ContainsKey("mergeOrderIds") ? item["mergeOrderIds"].ToString() : "",
                waybillPrintStatus = item.ContainsKey("waybillPrintStatus") ? item["waybillPrintStatus"].ToString() : "0",
                lastShipTime = item.ContainsKey("lastShipTime") ? item["lastShipTime"].ToString() : ""
            };
        }
        //step 2
        public static List<Product> ToErpProducts(this JsonData erpProducts)
        {
            var list = new List<Product>();
            foreach (JsonData item in erpProducts)
            {
                list.Add(new Product
                {
                    id = item["id"].ToString(),
                    subOrderId = item["subOrderId"].ToString(),
                    orderStatus = item.ContainsKey("orderStatus") ? item["orderStatus"].ToString() : "",
                    productCode = item.ContainsKey("productCode") ? item["productCode"].ToString() : "",
                    productName = item.ContainsKey("productName") ? item["productName"].ToString() : "",
                    skuId = item.ContainsKey("skuId") ? item["skuId"].ToString() : "",
                    skuCode = item.ContainsKey("skuCode") ? item["skuCode"].ToString() : "",
                    productPic = item.ContainsKey("productPic") ? item["productPic"].ToString() : "",
                    productNumber = item.ContainsKey("productNumber") ? (int)item["productNumber"] : 0,
                    productSpecDesc = item.ContainsKey("productSpecDesc") ? item["productSpecDesc"].ToString() : "",
                    productId = item.ContainsKey("productId") ? item["productId"].ToString() : "",
                });
            }
            return list;
        }
        //step 3
        public static List<MergeSubOrder> ToMergeSubOrders(this JsonData mergeSubOrders)
        {
            var list = new List<MergeSubOrder>();
            foreach (JsonData item in mergeSubOrders)
            {
                list.Add(new MergeSubOrder 
                {
                    id = item["id"].ToString(),
                    orderId = item["orderId"].ToString(),
                    sysOrderId = item["sysOrderId"].ToString(),
                    orderStatus = item["orderStatus"].ToString(),
                    erpProducts = item["erpProducts"].ToErpProducts()
                });
            }
            return list;
        }
        //step 4
        public static List<LogisticsCode> ToLogisticsCode(this JsonData logisticsCode)
        {
            List<LogisticsCode> list = new();

            foreach (JsonData item in logisticsCode)
            {
                list.Add(new LogisticsCode
                {
                    logisticsName = item.ContainsKey("logisticsName") ? item["logisticsName"].ToString() : "",
                    waybillFlag = item.ContainsKey("waybillFlag") ? item["waybillFlag"].ToString() : "",
                    logisticsCode = item.ContainsKey("logisticsCode") ? item["logisticsCode"].ToString() : "",
                    isOutwaybill = item.ContainsKey("isOutwaybill") ? item["isOutwaybill"].ToString() : "",
                    cpCode = item.ContainsKey("cpCode") ? item["cpCode"].ToString() : ""
                });
            }

            return list;
        }

        public static void ToView_订单_PrintData(this JsonData data)
        { 
            
        }
        public static string ToJsonStr(this JsonData jsonObj)
        {
            string jsonStr = jsonObj.ToJson();
            Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
            return reg.Replace(jsonStr, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        }

        #endregion




        #region 扩展·Model·orders集合/order
        /*
   
        public static async void UpdataControlBody(this List<OrderInfo> orders, UIFlowLayoutPanel Body, List<View_订单> 订单集合)
        {
            if (null == orders) { 订单集合.DisposeControls(); return; }

            if (orders.Count == 0) { 订单集合.DisposeControls(); return; }

            Body.Invoke(() =>
            {
                Body.Size = new Size(Body.Width, 895);
                int index = 0;
                foreach (var o in orders)
                {
                    if (index == 7) break;

                    //数量匹配
                    if (orders.Count > 订单集合.Count)
                    {
                        var 订单 = new View_订单(new OrderInfo());
                        Body.Add(订单);
                        订单集合.Add(订单);
                    }
                    else if (orders.Count < 订单集合.Count)
                    {
                        订单集合[订单集合.Count - 1].Dispose();
                    }

                    订单集合[index].UpdataFrom(o);

                    index++;
                }
            });

            await Task.Delay(100); // 确保UI更新完成

            if (orders.Count > 7)
            {
                await Body.InvokeAsync(() => {
                    for (int index = 7; index < orders.Count; index++)
                    {
                        //数量匹配
                        if (orders.Count > 订单集合.Count)
                        {
                            var 订单 = new View_订单(new OrderInfo());
                            Body.Add(订单);
                            订单集合.Add(订单);
                        }
                        else if (orders.Count < 订单集合.Count)
                        {
                            订单集合[订单集合.Count - 1].Dispose();
                        }

                        订单集合[index].UpdataFrom(orders[index]);
                    }
                });
            }
        }
        
      */

        #endregion


        #region 扩展·Model·HttpContent
        public static async Task<JsonData> ToJsonObj(this HttpContent content)
        {
            try
            {
                if (content.Headers != null && content.Headers.ContentEncoding.Contains("gzip"))
                {
                    using (var gzipStream = new GZipStream(await content.ReadAsStreamAsync(), CompressionMode.Decompress))
                    {
                        using (var reader = new StreamReader(gzipStream))
                        {
                            return JsonMapper.ToObject(await reader.ReadToEndAsync());
                        }
                    }
                }
                else
                {
                    return JsonMapper.ToObject(await content.ReadAsStringAsync());
                }
            }
            catch (Exception ex) { Debug.WriteLine("error6:" + ex.Message); return null; }

        }
        #endregion


        #region 扩展·Model·string·image/speak
        public static async Task<Image> ToImage(this string url)
        {
            return await Task.Run(async () =>
            {
                using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
                {
                    return Image.FromStream(await client.GetStreamAsync(url));
                }

            });

        }
        public static void ToSpeak(this string str)
        {
            Controller.speech.SpeakAsync(str);
        }
        #endregion




       


    }

  
}
